<template>
  <div class="body" v-loading="loading">
    <div>
      <el-button type="primary" size="small" icon="el-icon-check" @click="doSave" :disabled="header.status === 'audit'">&nbsp;保&nbsp;存&nbsp;</el-button>
      <el-button type="warning" size="small" icon="el-icon-s-promotion" @click="doUnAudit" v-if="header.status === 'audit'">&nbsp;反&nbsp;审&nbsp;</el-button>
      <el-button type="primary" size="small" icon="el-icon-s-promotion" @click="doAudit" v-else :disabled="!header.billNo">&nbsp;审&nbsp;核&nbsp;</el-button>
      <el-button type="success" size="small" icon="el-icon-refresh" @click="getBill(header.billNo, true)" v-if="header.billNo && header.status === 'save'">&nbsp;恢&nbsp;复&nbsp;</el-button>
      <el-button type="danger" size="small" icon="el-icon-delete" @click="doDelete" v-if="header.billNo && header.status === 'save'">&nbsp;删&nbsp;除&nbsp;</el-button>
      <el-button type="success" size="small" icon="el-icon-download" @click="doDownload" v-if="header.status === 'audit'">下载箱号详细</el-button>
      <el-button type="info" size="small" icon="el-icon-back" @click="gotoList">&nbsp;返&nbsp;回&nbsp;</el-button>
    </div>
    <el-form ref="form" :model="header" size="small" label-width="80px" :inline="true" class="header">
      <div class="audit_icon iconfont icon-yishenhe" v-if="header.status === 'audit'"></div>
      <div class="header_row">
        <el-form-item style="width:260px;" label="单号">{{ header.billNo || '-' }}</el-form-item>
        <el-form-item style="width:500px;" prop="materialNo" label="物料" :rules="[{ required: true, trigger:['blur', 'change'], message: '请输入此项内容' } ]">
          <el-select filterable remote :remote-method="e => getMaterialList(e)"  @change="setMaterialValue" v-model="header.materialNo" :disabled="header.status === 'audit'" size="small" clearable class="material" placeholder="请输入物料编码或者名称">
            <el-option v-for="item in this.materialList" :key="item.fNumber" :label="item.fNumber + '：' + item.fName + ' ' + item.fSpecification" :value="item.fNumber" />
          </el-select>
        </el-form-item>
        <el-form-item style="width:260px;" prop="supplierNo" label="供应商" :rules="[{ required: true, trigger:['blur', 'change'], message: '请输入此项内容' } ]">
          <el-select filterable remote :remote-method="e => getSupplierList(e)" v-model="header.supplierNo" size="small" :disabled="header.status === 'audit'" clearable placeholder="请输入编码或者名称">
            <el-option v-for="item in supplierList" :key="item.fNumber" :label="item.fNumber + '：' + item.fName" :value="item.fNumber" />
          </el-select>
        </el-form-item>
      </div>
      <div class="header_row">
        <el-form-item style="width:260px;" prop="batchNo" label="批号" :rules="[{ required: true, trigger:['blur', 'change'], message: '请输入此项内容' } ]">
          <el-input size="small" v-model="header.batchNo" clearable :disabled="header.status === 'audit'"></el-input>
        </el-form-item>
<!--        <el-form-item style="width:500px;" prop="supplierNo" label="供应商" :rules="[{ required: true, trigger:['blur', 'change'], message: '请输入此项内容' } ]">-->
<!--          <el-select filterable remote :remote-method="e => getSupplierList(e)"  @change="setSupplierValue" v-model="header.supplierNo" :disabled="header.status === 'audit'" size="small" clearable class="material" placeholder="请输入供应商编码或者名称">-->
<!--            <el-option v-for="item in this.supplierList" :key="item.fNumber" :label="item.fNumber + '：' + item.fName" :value="item.fNumber" />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--      </div>-->
<!--      <div class="header_row">-->
        <el-form-item class="produceDate" style="width:260px;" prop="produceDate" label="生产日期">
          <el-date-picker size="small" v-model="header.produceDate" clearable style="width: 150px;" :disabled-date="limitProduceDate" :disabled="header.status === 'audit'" />
        </el-form-item>
        <el-form-item prop="exp" label="保质期" class="p3">
          <el-input-number size="small" v-model="header.exp" :precision="0" style="width: 150px;" :min="1" :disabled="header.status === 'audit'" />
          <span class="comment">天</span>
        </el-form-item>
        <el-form-item prop="purCount" label="总重"  :rules="[{ required: true, trigger:['blur', 'change'], message: '请输入此项内容' } ]" class="p3">
          <el-input-number size="small" v-model="header.purCount" :precision="2" style="width: 150px;" :min="0" :disabled="header.status === 'audit'" />
          <span class="comment">称重差额：{{ ((header.count || 0) - (header.purCount || 0)).toFixed(2) }}</span>
        </el-form-item>
      </div>
      <div class="header_row">
        <el-form-item prop="remark" label="备注">
          <el-input style="width: 400px" size="small" type="text" v-model="header.remark" :disabled="header.status === 'audit'" />
        </el-form-item>
      </div>
    </el-form>
    <div class="detail_header">
      <div>
        <template v-if="!header.status || header.status === 'save'">
          <el-button type="danger" size="small" icon="el-icon-delete" @click="deleteDetail">删除选择行</el-button>
          <el-button type="danger" size="small" icon="el-icon-delete" @click="deleteDetail0">删除重量0的分录行</el-button>
          <el-button type="primary" size="small" icon="el-icon-plus" @click="addDetail">添加分录行</el-button>
          <batch-add-row-dialog ref="batchAddRowDialog" box-no-type="CGSH" @success="batchAddDetail"></batch-add-row-dialog>
        </template>
      </div>
      <div class="stat">
        <div><div class="label">称重</div><div class="value">{{ header.count ? Number(header.count.toFixed(6)): '0.00' }}</div></div>
        <div><div class="label">箱数</div><div class="value">{{ boxList?.length ?? 0 }}</div></div>
        <div><div class="label">已入库重量</div><div class="value">{{ header.inStockCount || '0.00' }}</div></div>
        <div><div class="label">已入库箱数</div><div class="value">{{ header.inStockBoxCount || 0 }}</div></div>
      </div>
    </div>
    <el-table :data="boxList" class="detail" height="calc(100vh - 325px)" @selection-change="selectChange">
      <el-table-column label="#" width="60" align="center" type="selection" v-if="!header.status || header.status === 'save'"></el-table-column>
      <el-table-column label="No." width="60" align="right" type="index"></el-table-column>
      <el-table-column label="箱号" width="160" prop="boxNo"></el-table-column>
      <el-table-column label="重量" width="170" align="center">
        <template #default="scope">
          <el-input-number :id="`w_row_${ scope.$index }`" ref="w_row" size="small" v-model="scope.row.count" :precision="2" style="width: 150px;" :min="0" @keyup.enter="addDetailOnRow($event, scope)" @change="changeDetailCount" :disabled="header.status === 'audit' || scope.row.inStock === true" />
        </template>
      </el-table-column>
      <el-table-column label="备注" width="250" align="remark">
        <template #default="scope">
          <el-input type="text" size="small" v-model="scope.row.comment" :disabled="header.status === 'audit'"/>
        </template>
      </el-table-column>
      <el-table-column label="是否入库" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.inStock? 'success': 'warning'">{{ scope.row.inStock? '已入库': '未入库' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="rfid" prop="rfid" width="100" align="center">
        <template #default="scope">
          <el-popover v-if="scope.row.rfid" placement="bottom" title="rfid" :width="280" trigger="click" :content="scope.row.rfid">
            <template #reference>
              <el-tag type="success" style="cursor: pointer">已关联</el-tag>
            </template>
          </el-popover>
          <el-tag v-else type="warning">未关联</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="入库时间" prop="perInTime" width="140" align="center">
        <template #default="scope">{{ formatDate(scope.row.perInTime) }}</template>
      </el-table-column>
      <el-table-column label="入库单号" align="left" prop="perInBillNo"></el-table-column>
      <el-table-column label="操作" width="90" fixed="right" v-if="!header.status || header.status === 'save'">
        <template #default="scope">
          <el-button type="text" style="color: var(--el-color-danger)" icon="el-icon-delete" @click="deleteRow(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { getBoxNo } from '../../utils'
import BatchAddRowDialog from "../components/batchAddRowDialog.vue";

export default {
  components: {BatchAddRowDialog},
  data() {
    return {
      loading: false,
      materialLoading: false,
      materialList: [],
      supplierLoading: false,
      supplierList: [],
      header: {},
      boxList: [],
      selection: [],
      row: 0
    }
  },
  async mounted() {
    let billNo = this.$route.query.billNo
    if (billNo) {
      return this.getBill(billNo)
    }
  },
  methods: {
    formatDate(date) {
      if (!date) return ''
      return dayjs(date).format('YYYY-MM-DD HH:mm')
    },
    gotoList() {
      return this.$router.push('/purchase/purColList')
    },
    async getBill(billNo, reset) {
      if (reset) {
        try {
          await this.$confirm('恢复后未保存数据将被清除，确定恢复吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
        } catch(e) {
          return
        }
      }
      this.loading = true
      try {
        let res = await this.callApi('get_purcol_bill_detail', { billNo })
        if (res.res) {
          this.materialList = [{ fNumber: res.header.materialNo, fName: res.header.materialName, fSpecification: res.header.materialSpec }]
          this.supplierList = [{ fNumber: res.header.supplierNo, fName: res.header.supplierName }]
          this.header = res.header || {}
          this.boxList = res.boxList || []
          this.changeDetailCount()
        }
      } finally {
        this.loading = false
      }
    },
    async doDownload() {
      try {
        await this.$confirm(`确定下载吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch(e) {
        return
      }
      this.loading = true
      try {
        let res = await this.callApi('download_purcol_bill_barcode', { billNo: this.header.billNo })
        if (!res.res) {
          return
        }
        this.$message.success(`已下载!`)
      } finally {
        this.loading = false
      }
    },
    async doDelete() {
      try {
        await this.$confirm('确定删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch(e) {
        return
      }
      this.loading = true
      try {
        let res = await this.callApi('delete_purcol_bill', { billNo: this.header.billNo })
        if (!res.res) {
          return
        }
        return this.gotoList()
      } finally {
        this.loading = false
      }
    },
    async doAudit() {
      this.loading = true
      try {
        let res = await this.callApi('audit_purcol_bill', { billNo: this.header.billNo })
        if (!res.res) {
          return
        }
        this.header.status = res.status
        this.$message.success('审核完成!')
      } finally {
        this.loading = false
      }
    },
    async doUnAudit() {
      this.loading = true
      try {
        let res = await this.callApi('unaudit_purcol_bill', { billNo: this.header.billNo })
        if (!res.res) {
          return
        }
        this.header.status = res.status
        this.$message.success('反审完成!')
      } finally {
        this.loading = false
      }
    },
    doSave() {
      this.$refs.form.validate(async valid => {
        if (!valid) {
          return
        }
        if (this.boxList.length === 0) {
          this.$message.error('没有分录!')
          return
        }
        for(let i = 0; i < this.boxList.length; i++) {
          if (!this.boxList[i].count) {
            this.$message.error('分录行没有重量!')
            return
          }
        }
        this.loading = true
        let boxList = []
        for(let i = 0; i < this.boxList.length; i++) {
          boxList.push({ boxNo: this.boxList[i].boxNo, count: this.boxList[i].count, comment: this.boxList[i].comment })
        }
        let supplierName
        for (let i = 0; i < this.supplierList.length; i++) {
          if (this.supplierList[i].fNumber === this.header.supplierNo) {
            supplierName = this.supplierList[i].fName
          }
        }
        let param = {
          billNo: this.header.billNo,
          materialNo: this.header.materialNo,
          materialName: this.header.materialName,
          materialSpec: this.header.materialSpec,
          batchNo: this.header.batchNo,
          supplierNo: this.header.supplierNo,
          supplierName: supplierName,
          remark: this.header.remark,
          produceDate: dayjs(this.header.produceDate).format('YYYY-MM-DD'),
          exp: this.header.exp,
          purCount: this.header.purCount,
          boxList
        }
        try {
          let res = await this.callApi('save_purcol_bill', param)
          if (!res.res) {
            return
          }
          this.header.billNo = res.billNo
          this.$message.success('保存完成!')
        } finally {
          this.loading = false
        }
      })
    },
    async getMaterialList(val) {
      if (!val) {
        this.materialList = []
        return
      }
      this.materialLoading = true
      try {
        const res = await this.callApi('get_material_by_key', { key: val, pageSize: 20 })
        if (!res.res) return
        this.materialList = res.data
      } finally {
        this.materialLoading = false
      }
    },
    setMaterialValue() {
      if (this.materialList && this.header.materialNo) {
        for(let i = 0; i < this.materialList.length; i++) {
          if (this.materialList[i].fNumber === this.header.materialNo) {
            this.header.materialName = this.materialList[i].fName
            this.header.materialSpec = this.materialList[i].fSpecification
            break
          }
        }
      } else {
        this.header.materialName = ''
        this.header.materialSpec = ''
      }
    },
    async getSupplierList(val) {
      if (!val) {
        this.supplierList = []
        return
      }
      this.supplierLoading = true
      try {
        const res = await this.callApi('get_supplier_by_key', { key: val, pageSize: 20 })
        if (!res.res) return
        this.supplierList = res.data
      } finally {
        this.supplierLoading = false
      }
    },
    setSupplierValue() {
      if (this.supplierList && this.header.supplierNo) {
        for(let i = 0; i < this.supplierList.length; i++) {
          if (this.supplierList[i].fNumber === this.header.supplierNo) {
            this.header.supplierName = this.supplierList[i].fName
            break
          }
        }
      } else {
        this.header.supplierName = ''
      }
    },
    limitProduceDate(d) {
      return dayjs(d).isAfter(dayjs())
    },
    selectChange(data) {
      this.selection = data
    },
    async deleteDetail() {
      try {
        await this.$confirm('确定删除吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch(e) {
        return
      }
      this.selection.forEach(sel => {
        for(let i = 0; i < this.boxList.length; i++) {
          if (this.boxList[i].boxNo === sel.boxNo) {
            this.boxList.splice(i, 1)
            break
          }
        }
      })
    },
    async deleteDetail0() {
      try {
        await this.$confirm('确定删除吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch(e) {
        return
      }
      for(let i = this.boxList.length - 1; i >= 0; i--) {
        if (this.boxList[i].count === 0) {
          this.boxList.splice(i, 1)
        }
      }
      this.changeDetailCount()
    },
    addDetail() {
      this.boxList.push({
        count: 0,
        boxNo: getBoxNo('CGSH'),
        inStock: false,
        perInBillNo: ''
      })
    },
    batchAddDetail(boxList) {
      this.boxList = this.boxList.concat(boxList)
      this.changeDetailCount()
    },
    addDetailOnRow(e, scope) {
      if (scope.$index === this.boxList.length - 1) {
        if (e.keyCode === 13) {
          this.addDetail()
          this.$nextTick(() => {
            document.querySelector('#w_row_' + ( scope.$index + 1 ) + ' input').focus()
            document.querySelector('#w_row_' + ( scope.$index + 1 ) + ' input').select()
          })
        }
      }
    },
    async deleteRow(idx) {
      try {
        await this.$confirm('确定删除吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch(e) {
        return
      }
      this.boxList.splice(idx, 1)
      this.changeDetailCount()
    },
    changeDetailCount() {
      let total = 0
      for(let i = 0; i < this.boxList.length; i++) {
        total += this.boxList[i].count
      }
      this.header.count = total
      this.header.purCount = this.header.count
    }
  }
}
</script>

<style lang="scss" scoped>
.body {
  padding: 20px 0;
  .header {
    margin-top: 20px;
    position: relative;
    .header_row {
      display: flex;
      >div {
        flex-shrink: 0;
      }
      :deep(.produceDate) {
        .el-input {
          width: 100%!important;
        }
      }
    }
    .audit_icon {
      position: absolute;
      top: -10px;
      left: 60px;
      font-size: 48px;
      color: red;
    }
    .material {
      width: 100%;
    }
    .p3 {
      :deep(.el-form-item__content) {
        display: flex;
        .comment {
          margin-left: 10px;
          word-break: keep-all;
        }
      }
    }
  }
  .detail_header {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
    .stat {
      display: flex;
      font-size: 15px;
      >div {
        display: flex;
        align-items: baseline;
        line-height: 32px;
        .label {
          text-align: right;
          margin-right: 5px;
          color: #aaa;
        }
        .value {
          min-width: 50px;
          margin-right: 10px;
          color: #666;
        }
      }
    }
  }
}
</style>
